// routes/comments.js
const express = require('express');
const { body, query, param } = require('express-validator');
const {authMiddleware} = require('../tool/middleWare');
const express_validate = require('../tool/express_validator');
const {asyncHandler} = require('../tool/middleWare');
const {createOrderCommentWithTipService, replyCommentByAdvisorService} = require("../service/comment");


const router = express.Router();
// 订单评论 + 打赏
router.post(
    '/create',
    authMiddleware,
    body('orderId').isInt({ min: 1 }).toInt(),
    body('advisorId').isInt({ min: 1 }).toInt(),
    body('rating').isFloat({ min: 0, max: 5 }),
    body('content').isString().trim().isLength({ max: 5000 }),
    body('isToTip').isInt({ min: 0, max: 1 }).toInt(),
    body('tipCoin').custom((value, { req }) => {
        const isToTip = Number(req.body.isToTip);
        if (isToTip === 1) {
            const v = Number(value);
            if (!Number.isInteger(v) || v <= 0) {
                throw new Error('tipCoin 必须为正整数且大于 0');
            }
        }
        return true;
    }),
    express_validate,
    asyncHandler(async (req, res) => {
        const userId = req.loginUser.id; // 从登录态取
        const data = await createOrderCommentWithTipService({
            userId,
            orderId: req.body.orderId,
            advisorId: req.body.advisorId,
            rating: Number(req.body.rating),
            content: req.body.content || '',
            isToTip: Number(req.body.isToTip) || 0,
            tipCoin: Number(req.body.tipCoin || 0),
        });
        return res.success(data, '评价提交成功');
    })
);


//顾问回复评论
router.post(
    '/reply',
    authMiddleware,
    body('commentId').isInt({ min: 1 }).toInt(),
    body('replyContent').isString().trim().isLength({ min: 1, max: 5000 }),
    express_validate,
    asyncHandler(async (req, res) => {
        const advisorId = req.loginUser.id; // 顾问身份从登录态取
        const data = await replyCommentByAdvisorService({
            advisorId,
            commentId: req.body.commentId,
            replyContent: req.body.replyContent,
        });
        return res.success(data, '回复成功');
    })
);

module.exports = router;

module.exports = router;